package com.taikang.hmp.hservice.doctor.chineseevalmodel.evaOfTraChiMedicine.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.taikang.hmp.hservice.doctor.chineseevalmodel.bean.Hdbzdcchmedicine;
import com.taikang.hmp.hservice.doctor.chineseevalmodel.bean.Hdmdevalresult;
import com.taikang.hmp.hservice.doctor.chineseevalmodel.bean.Hdmdpaper;
import com.taikang.hmp.hservice.doctor.chineseevalmodel.bean.SolarTermInfo;
import com.taikang.hmp.hservice.doctor.chineseevalmodel.evaOfTraChiMedicine.service.IEvaOfTraChiMedicineService;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.bean.Dictionary;

public class EvaOfTraChiMedicineServiceImpl extends BaseServiceImpl implements IEvaOfTraChiMedicineService{
	
	/**
	 * 实症与虚症的优先算法 
	 * 实症与虚症比较，返回偏颇体质类型的数组，rtn[0]存储体质类型角标，rtn[1]中0表示虚症，1表示实症
	 * @param xz
	 * @param sz
	 * @return
	 */
	public static int[] sxCompare(double[] xz,double[] sz,double[] xzSort,double[] szSort){
		int[] rtn = new int[2];
		Arrays.sort(xzSort);
		Arrays.sort(szSort);
		System.out.println(Arrays.toString(xzSort));
		System.out.println(Arrays.toString(szSort));
		if(xzSort[xzSort.length-1] >= szSort[szSort.length-1]){
			int index = yxTz(xzSort[xzSort.length-1],xz);
			rtn[0] = index;
			rtn[1] = 0;
		}else{
			int index = yxTz(szSort[szSort.length-1],sz);
			rtn[0] = index;
			rtn[1] = 1;
		}
		return rtn;
	}
	/**
	 * 实症或者虚证中相同转化分的优先体质算法
	 * @param a
	 * @param xz
	 * @return
	 */
	public static int yxTz(double max,double[] xz){
		int index = 0;
		if(xz[0] == max){
			index = 0;
		}else if(xz[1] == max){
			index = 1;
		}else if(xz[2] == max){
			index = 2;
		}else if(xz[3] == max){
			index = 3;
		}
		return index;
	}
	/**
	 * 计算每种体质的转化分数
	 * @param questionsStr
	 * @param scores
	 * @param constitutionsStr
	 * @return
	 */
	public static double[] countScore(String[] scores,String constitutionsStr){
		
		int[] constitutionsScore = new int[9];
		int[] constitutionNum = new int[9];
		double[] countScore = new double[9];
			String[] constitutions = constitutionsStr.split(",");
			for(int i=0;i<constitutions.length;i++){
				if("1".equals(constitutions[i])){
					constitutionsScore[0] = constitutionsScore[0] + Integer.valueOf(scores[i]);
					constitutionNum[0] ++;
				}else if("2".equals(constitutions[i])){
					constitutionsScore[1] = constitutionsScore[1] + Integer.valueOf(scores[i]);
					constitutionNum[1] ++;
				}else if("3".equals(constitutions[i])){
					constitutionsScore[2] = constitutionsScore[2] + Integer.valueOf(scores[i]);
					constitutionNum[2] ++;
				}else if("4".equals(constitutions[i])){
					constitutionsScore[3] = constitutionsScore[3] + Integer.valueOf(scores[i]);
					constitutionNum[3] ++;
				}else if("5".equals(constitutions[i])){
					constitutionsScore[4] = constitutionsScore[4] + Integer.valueOf(scores[i]);
					constitutionNum[4] ++;
				}else if("6".equals(constitutions[i])){
					constitutionsScore[5] = constitutionsScore[5] + Integer.valueOf(scores[i]);
					constitutionNum[5] ++;
				}else if("7".equals(constitutions[i])){
					constitutionsScore[6] = constitutionsScore[6] + Integer.valueOf(scores[i]);
					constitutionNum[6] ++;
				}else if("8".equals(constitutions[i])){
					constitutionsScore[7] = constitutionsScore[7] + Integer.valueOf(scores[i]);
					constitutionNum[7] ++;
				}else {
					constitutionsScore[8] = constitutionsScore[8] + Integer.valueOf(scores[i]);
					constitutionNum[8] ++;
				}
			}
		for(int j=0;j<countScore.length;j++){
			countScore[j] = ((constitutionsScore[j] - constitutionNum[j])/(constitutionNum[j]*4.0))*100;
		}
		return countScore;
	}
	@Override
	public List<Dto> getQuestion(String id) {
		
			
		List<Object> resultList = super.getNewDao().queryForList("chiMedi_space.getQuestion",id);
		List<Dto> result = new ArrayList<Dto>();
		for (int i = 0; i < resultList.size(); i++) {
			Map map=(Map) resultList.get(i);
			Dto resultMap = new BaseDto();
			resultMap.put("detailid", map.get("detail_id").toString());
			resultMap.put("detailname", map.get("detail_name").toString());
			resultMap.put("questionid", map.get("question_id").toString());
			resultMap.put("questionname", map.get("question_name").toString());
			resultMap.put("questionvalue",map.get("question_value").toString().replaceAll("\"","'" ));
			resultMap.put("sex", map.get("sex").toString());
			resultMap.put("bz", map.get("bz").toString());
			result.add(resultMap);
		}
		return result;
		
	}
	@Override
	public List<Dto> saveQuestionrResult(String score, String bz, Dto dto) {
		String scores[]=score.split(",");
		//数组中转化分数依次为：阳虚 阴虚 气虚 痰湿 湿热 血瘀 特禀 气郁 平和
		double[] conversionScore =countScore(scores,bz);
		//虚症
		double[] xz = {conversionScore[2],conversionScore[0],conversionScore[1],conversionScore[6]};
		//实症
		double[] sz = {conversionScore[3],conversionScore[4],conversionScore[5],conversionScore[7]};
		//用于排序的实症和虚症
		double[] xzSort = {conversionScore[2],conversionScore[0],conversionScore[1],conversionScore[6]};
		double[] szSort = {conversionScore[3],conversionScore[4],conversionScore[5],conversionScore[7]};
		//虚症体质类型编号
		int[] xzType = {2,0,1,6};
		//实症体质类型编号
		int[] szType = {3,4,5,7};
		//排序
		Arrays.sort(xzSort);
		Arrays.sort(szSort);
		//哪种体质类型 （平和 阴虚 阳虚...）
		int constitution_type = 0;
		//判定结果 0 是 1基本是 2 否
		int grade = 0;
		//平和体质转化分>=60 其他8种体质转化分<30	是平和质
		if(conversionScore[8] >= 60 && conversionScore[0] < 30 && conversionScore[1] < 30 && conversionScore[2] < 30 
				&& conversionScore[3] < 30 && conversionScore[4] < 30 && conversionScore[5] < 30 && conversionScore[6] < 30 && conversionScore[7] < 30){
			grade = 0;
			constitution_type = 9;
		//平和体质转化分>=60 其他8种体质转化分<40	基本是平和质
		}else if(conversionScore[8] >= 60 && conversionScore[0] < 40 && conversionScore[1] < 40 && conversionScore[2] < 40 
				&& conversionScore[3] < 40 && conversionScore[4] < 40 && conversionScore[5] < 40 && conversionScore[6] < 40 && conversionScore[7] < 40){
			grade = 1;
			constitution_type = 9;
		}else{
			if(xzSort[xzSort.length-1] >= 30 || szSort[szSort.length-1] >= 30){
				int[] rtn = sxCompare(xz, sz, xzSort, szSort);
				if(rtn[1] == 0){
					constitution_type = xzType[rtn[0]] + 1;
					if (xzSort[xzSort.length-1] < 40) {
						grade = 1;
					}
				}else{
					constitution_type = szType[rtn[0]] + 1;
					if (szSort[szSort.length-1] < 40) {
						grade = 1;
					}
				}
			} else {
				constitution_type=9;
				grade=1;
			}
		}
		String datetime=date("yyyy-MM-dd HH:mm:ss");
		String	index=grade==0?"是":"基本是";
//		String tzlx=returnMap(constitution_type);
		SolarTermInfo info=new SolarTermInfo();
		int sddd=info.getIndex();
		//constitution_type为体质
		String url=showURL(constitution_type,sddd);
		
		Hdmdevalresult result = new Hdmdevalresult();
		result.setEvalid(java.util.UUID.randomUUID().toString());
		result.setCustomid(dto.getAsString("customerid"));
		result.setEvalname("中医体质评估");
		result.setTaginfo("1");
		result.setEvalstate("1");
		result.setEvaldate(datetime);
		result.setEvalinfo(url);
		result.setSourcecd(dto.getAsString("requestsource"));
		result.setOperater(dto.getAsString("uid"));
		result.setOperatedate(new Date());
		super.getNewDao().insert("chiMedi_space.saveQuestionrResult", result);
		
		//回现到页面数据
		Dto resultMap=new BaseDto();
		List<Dto> results = new ArrayList<Dto>();
		resultMap.put("url", url);
		resultMap.put("type", constitution_type);
		results.add(resultMap);
		return results;
	}
	public String date(String pat){
		
		SimpleDateFormat format = new SimpleDateFormat(pat);
		return format.format(new Date());
	}
	
	
	public String returnMap(int key){
		Map<Integer,String> map=new HashMap<Integer, String>();
//		阳虚 阴虚 气虚 痰湿 湿热 血瘀 特禀 气郁 平和
		map.put(1,"阳虚质" );
		map.put(2, "阴虚质");
		map.put(3, "气虚质");
		map.put(4, "痰湿质");
		map.put(5, "湿热质");
		map.put(6, "血瘀质");
		map.put(7, "特禀质");
		map.put(8, "气郁质");
		map.put(9, "平和质");
		return map.get(key);
		
	}
	
	public String showURL(int type,int index){
		
		String yang="/zytzpg/yang.html?index="+index;
		String yinxu="/zytzpg/yinxu.html?index="+index;
		String qixu="/zytzpg/qixu.html?index="+index;
		String tan="/zytzpg/tan.html?index="+index;
		String shi="/zytzpg/shi.html?index="+index;
		String xueyu="/zytzpg/xueyu.html?index="+index;
		String te="/zytzpg/te.html?index="+index;
		String qiyu="/zytzpg/qiyu.html?index="+index;
		String pinghe="/zytzpg/pinghe.html?index="+index;
		String url=type==1?yang:(type==2?yinxu:(type==3?qixu:( type==4?tan: ( type==5?shi :(type==6?xueyu:(type==7?te:(type==8?qiyu:pinghe  )  )   ) )  ))) ;
		
		return url;
	}
	
	
	
	@Override
	public List<Dto> getQuestionrResult(Dto paramDto) {
		String type=paramDto.getAsString("assessType");
		String customerid=paramDto.getAsString("customerid");
		Map<String,String> map=new HashMap<String, String>();
		map.put("type",type);
		map.put("customerid",customerid);
		List<Hdmdevalresult> list=super.getNewDao().queryForList("chiMedi_space.getQuestionrResult", map);
		
		//回现到页面数据
		Dto resultMap=new BaseDto();
		List<Dto> results = new ArrayList<Dto>();
		resultMap.put("url", list.get(0).getEvalinfo());
		results.add(resultMap);
		return results;
	}
	@Override
	public Hdbzdcchmedicine getJqys(Dto paramDto) {
		
		String index=paramDto.getAsString("index");
		String sz[]={ "小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"  }; 
		String tz=paramDto.getAsString("tz");
		String jq=sz[Integer.valueOf(index)];
		String tzName=returnMap(Integer.valueOf(tz));
		Map<String,String> map=new HashMap<String, String>();
		map.put("solor_term",jq);
		map.put("tcm_constitution",tzName);
		
		List<Hdbzdcchmedicine> list=super.getNewDao().queryForList("chiMedi_space.getJqys", map);
		return list.get(0);
	}
	@Override
	public Dto getCorporeitySolar(Dto paramDto) {
		Dto resultMap = new BaseDto();
		//逛逛用户不查询数据
		if(!"f8b6eed7-ead2-47c7-ac25-9d7d088113a1".equals(paramDto.getAsString("customerid"))){
			Hdmdevalresult result = (Hdmdevalresult)super.getNewDao().queryForObject("chiMedi_space.getCorporeitySolar", paramDto.getAsString("customerid"));
			if(result!=null){
				SolarTermInfo info=new SolarTermInfo();
				String solar = info.getSoralTerms();
				String evalinfo = result.getEvalinfo();
				resultMap.put("solar", solar);
				if(evalinfo.contains("yang")){
					resultMap.put("corporeity", "阳虚质");
				}else if(evalinfo.contains("yinxu")){
					resultMap.put("corporeity", "阴虚质");
				}else if(evalinfo.contains("qixu")){
					resultMap.put("corporeity", "气虚质");
				}else if(evalinfo.contains("tan")){
					resultMap.put("corporeity", "痰湿质");
				}else if(evalinfo.contains("shi")){
					resultMap.put("corporeity", "湿热质");
				}else if(evalinfo.contains("xueyu")){
					resultMap.put("corporeity", "血瘀质");
				}else if(evalinfo.contains("te")){
					resultMap.put("corporeity", "特禀质");
				}else if(evalinfo.contains("qiyu")){
					resultMap.put("corporeity", "气郁质");
				}else if(evalinfo.contains("pinghe")){
					resultMap.put("corporeity", "平和质");
				}
			}
		}
		return resultMap;
	}
}
